package shells

import (
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
	"io"
)

type Options struct {
	command      string
	workingDir   string
	environments map[string]string
	args         []string

	needPty bool //是否支持交互式

	log    *logrus.Logger
	writer io.Writer
}

func Terraform(command string, args ...string) *Options {
	opts := New(command, args...)
	if len(args) > 0 {
		opts.needPty = isTerraformCommandThatNeedsPty(args[0])
	}
	return opts
}

func New(command string, args ...string) *Options {
	options := &Options{
		command: command,
		args:    args,
	}
	options.WithLogger(logrus.StandardLogger())
	return options
}

func (o *Options) WorkingDir(dir string) *Options {
	o.workingDir = dir
	return o
}

func (o *Options) Envs(env map[string]string) *Options {
	o.environments = env
	return o
}
func (o *Options) Env(key, val string) *Options {
	if o.environments == nil {
		o.environments = make(map[string]string)
	}
	o.environments[key] = val
	return o
}

func (o *Options) WithWriter(writer io.Writer) *Options {
	o.writer = writer
	return o
}

func (o *Options) WithLogger(log *logrus.Logger) *Options {
	o.log = log
	return o
}

func (o *Options) Run() error {
	return runShellCommand(o)
}

func (o *Options) RunWithOutput() (stdout string, stderr string, err error) {
	return runShellCommandWithOutput(o)
}

// isTerraformCommandThatNeedsPty returns true if the sub command of terraform we are running requires a pty.
func isTerraformCommandThatNeedsPty(command string) bool {
	return util.Contain([]string{"console"}, command)
}
